import axios, { AxiosInstance } from "axios";
import {ref,getCurrentInstance} from 'vue';
import { ElMessage } from 'element-plus'
import Vue from 'vue'
interface AxiosOptions {
  type?:'get'|string,
  url:string,
  data?:any,
  all?:boolean
}
const w:any = window;
const base: string =  w.location.protocol+"//"+w.location.host+'/boke/index.php';
function request(options:AxiosOptions):Promise<any>{
   const data = ref("c");
   let success;
   let fail;
   let instance:any = getCurrentInstance();
   const axiosobj:AxiosInstance = axios.create({
    baseURL: base,
    timeout: 10000,
   });
   return new Promise((r,j)=>{
    if(options.type=='post'){
      const formdata:FormData = new FormData();
      for(const key in options.data){
          formdata.append(key,options.data['key']);
      };
      axiosobj.post(options.url,formdata).then(({data})=>{
        if(data.status!=200){
          ElMessage({
            type:"error",
            message:data.msg
          });
          j(data.msg)
        }else{
          options.all?r(data):r(data.msg)
        }
      }).catch((err)=>{
        ElMessage({
          type:"error",
          message:err
        });
        j(err)
      })
     }else{
      axiosobj.get(options.url,{params:options.data}).then(({data})=>{
        if(data.status!=200){
          ElMessage({
            type:"error",
            message:data.msg
          });
          j(data.msg)
        }else{
          options.all?r(data):r(data.msg)
        }
        
      }).catch((err)=>{
         ElMessage({
          type:"error",
          message:err
        });
         j(err)
      })
     }
   })
}
export {request};